'use strict'

const path = require('path')
const { app, BrowserWindow } = require('electron')
const electronLocalShortcut = require('electron-localshortcut')
const log4js = require('log4js')

const AppConfig = require('../configuration')

let Common =  (AppConfig.readSettings('language') === 'zh_CN') ? require('../common_cn') : require('../common')

class SettingsWindow {
  constructor() {
    this.logger = log4js.getLogger("SETTING")
    this.logger.level = AppConfig.readSettings("logger-level")
    this.settingsWindow = null
  }

  createSettingsWindow() {
    this.logger.debug("create window")
    this.settingsWindow = new BrowserWindow({
      width: Common.WINDOW_SIZE_SETTINGS.width,
      height: Common.WINDOW_SIZE_SETTINGS.height * 0.9,
      resizable: false,
      fullscreenable: false,
      show: false,
      frame: true,
      alwaysOnTop: true,
      icon: '../renderer/assets/icon.png',
      titleBarStyle: 'hidden',
      webPreferences: {
        javascript: true,
        nodeIntegration: true,
        contextIsolation: false,
        webSecurity: true,
        preload: path.join(__dirname, "../renderer/lib/version.js")
      }
    })

    this.initWindowEvents()
    this.initSettingsWindowShortcut()

    this.settingsWindow.loadURL(`file://${path.join(__dirname, '/../renderer/views/settings.html')}`)
  }

  initWindowEvents() {
    this.settingsWindow.on('close', () => {
      this.logger.debug("close window")
      this.unregisterLocalShortCut()
      this.isShown = false
    })

    this.settingsWindow.on('closed', () => {
      this.logger.debug("clean memory")
      this.settingsWindow = null
    })

    this.settingsWindow.on('window-all-closed', () => {
      app.quit()
    })

    this.settingsWindow.once('ready-to-show', () => {
      this.logger.debug("ready to show")
      this.settingsWindow.show()
    })
  }

  show() {
    this.logger.debug("show window")
    if (!this.settingsWindow) {
      this.createSettingsWindow()
    }
    this.settingsWindow.show()
    this.isShown = true
  }

  hide() {
    this.logger.debug("hide window")
    this.settingsWindow.hide()
    this.isShown = false
  }

  registerLocalShortcut() {
    electronLocalShortcut.register(this.settingsWindow, 'Esc', () => {
      this.settingsWindow.close()
    })
  }

  unregisterLocalShortCut() {
    electronLocalShortcut.unregisterAll(this.settingsWindow)
  }

  initSettingsWindowShortcut() {
    this.registerLocalShortcut()
  }
}

module.exports = SettingsWindow
